package cn.edu.nju.software.action.order;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import cn.edu.nju.software.bean.show.BookItemInOrder;
import cn.edu.nju.software.bean.show.OrderShow;
import cn.edu.nju.software.bean.show.UserShow;
import cn.edu.nju.software.bean.storage.Order;
import cn.edu.nju.software.service.intf.OrderService;
import cn.edu.nju.software.util.Constants;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class ViewOrderAction extends ActionSupport implements SessionAware {

	private int id;
	private OrderShow orderShow;
	private String[] orderAddress;
	private List<BookItemInOrder> orderBooks;
	private OrderService orderService;
	private Map<String, Object> session;

	public void setId(int id) {
		this.id = id;
	}

	public OrderShow getOrderShow() {
		return orderShow;
	}

	public String[] getOrderAddress() {
		return orderAddress;
	}

	public List<BookItemInOrder> getOrderBooks() {
		return orderBooks;
	}

	public void setOrderService(OrderService orderService) {
		this.orderService = orderService;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
	
	@Override
	public String execute() throws Exception {
		@SuppressWarnings("unchecked")
		Map<Integer, OrderShow> ordersMap = (Map<Integer, OrderShow>) session.get(Constants.SESSION_ORDERS);
		@SuppressWarnings("unchecked")
		Map<Integer, String[]> ordersAddressMap = (Map<Integer, String[]>) session.get(Constants.SESSION_ORDERS_ADDRESS);
		@SuppressWarnings("unchecked")
		Map<Integer, List<BookItemInOrder>> ordersBooksMap = 
			(Map<Integer, List<BookItemInOrder>>) session.get(Constants.SESSION_ORDERS_BOOKS);
		if (ordersMap == null || (orderShow = ordersMap.get(id)) == null) {
			Order order = orderService.getOrderById(id);
			orderShow = new OrderShow(order, new UserShow(orderService.getUsersByID(id)));
			orderAddress = order.getAddress().split(Constants.ADDRESS_SEPARATOR);
			orderBooks = orderService.getOrderBooks(id);
			if (ordersMap == null) {
				ordersMap = new LinkedHashMap<Integer, OrderShow>(1);
				ordersAddressMap = new LinkedHashMap<Integer, String[]>(1);
				ordersBooksMap = new LinkedHashMap<Integer, List<BookItemInOrder>>(1);
			}
			ordersMap.put(id, orderShow);
			ordersAddressMap.put(id, orderAddress);
			ordersBooksMap.put(id, orderBooks);
		} else {
			orderAddress = ordersAddressMap.get(id);
			orderBooks = ordersBooksMap.get(id);
		}
		return SUCCESS;
	}
}
